class Calculator:
    def __init__(self, expression):
        self.expression = expression.replace(" ", "")  # 去除空格
        self.index = 0

    def parse(self):
        """启动解析，返回结果或错误"""
        try:
            result = self.E()
            if self.index < len(self.expression):  # 输入未完全消费
                raise SyntaxError("多余的字符")
            return result
        except SyntaxError as e:
            return f"错误: {e}"

    def next_token(self):
        """获取当前字符"""
        if self.index < len(self.expression):
            return self.expression[self.index]
        return '$'  # 结束标记

    def consume(self, expected):
        """匹配并消费字符"""
        if self.next_token() == expected:
            self.index += 1
        else:
            raise SyntaxError(f"预期 '{expected}' 但遇到 '{self.next_token()}'")

    def E(self):
        """E -> T E'"""
        value = self.T()
        return self.E_prime(value)

    def E_prime(self, inherited_value):
        """E' -> + T E' | - T E' | ε"""
        if self.next_token() == '+':
            self.consume('+')
            return self.E_prime(inherited_value + self.T())
        elif self.next_token() == '-':
            self.consume('-')
            return self.E_prime(inherited_value - self.T())
        return inherited_value  # 空产生式

    def T(self):
        """T -> F T'"""
        value = self.F()
        return self.T_prime(value)

    def T_prime(self, inherited_value):
        """T' -> * F T' | / F T' | ε"""
        if self.next_token() == '*':
            self.consume('*')
            return self.T_prime(inherited_value * self.F())
        elif self.next_token() == '/':
            self.consume('/')
            denominator = self.F()
            if denominator == 0:
                raise SyntaxError("除以零错误")
            return self.T_prime(inherited_value / denominator)
        return inherited_value  # 空产生式

    def F(self):
        """F -> ( E ) | num"""
        if self.next_token() == '(':
            self.consume('(')
            value = self.E()
            self.consume(')')
            return value
        else:  # 处理数字
            start_index = self.index
            while self.next_token().isdigit() or self.next_token() == '.':
                self.index += 1
            if start_index == self.index:
                raise SyntaxError("数字预期但未找到")
            return float(self.expression[start_index:self.index])


# 测试用例
expressions = [
    "3 + 5 * (2 - 8)",
    "(1 + 2) * 3 / 3",
    "10 / (5 - 5)",  # 除零错误
    "2 +",  # 不完整表达式
    "3 * (4 + 2))"  # 多余右括号
]

for expr in expressions:
    calc = Calculator(expr)
    print(f"表达式: {expr}")
    print(f"结果: {calc.parse()}\n")
